﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace WebApplication1
{
    public partial class _Default : Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            var see = Session["Username"];

            if (see == null)
            {
                Response.Redirect("Login.aspx");
            }

            if (!IsPostBack)
            {
                FillData();
            }
        }

        private void FillData()
        {
            var sql = string.Format("select * from Task");

            var dt = DbHelper.GetData(sql);

            GrdList.DataSource = dt;
            GrdList.DataBind();
        }

        private string GetVal(int rowIndex,int colIndex)
        {
            var control = GrdList.Rows[rowIndex].Cells[colIndex];
            var res = control.Controls.Count > 0 ? ((TextBox)control.Controls[0]).Text : control.Text;
            return res;
        }

        protected void GrdList_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
        {

        }

        protected void GrdList_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            var id = GetVal(e.RowIndex, 0);

            var sql = string.Format("delete from Task where Id={0}", id);

            DbHelper.Exe(sql);

            FillData();
        }

        protected void GrdList_RowEditing(object sender, GridViewEditEventArgs e)
        {
            var id = GetVal(e.NewEditIndex, 0);
            Response.Redirect("TaskEdit.aspx?id="+id);
        }

        protected void GrdList_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {

        }

        protected void btnAdd_Click(object sender, EventArgs e)
        {
            Response.Redirect("TaskEdit.aspx");
        }

        protected void GrdList_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            GrdList.PageIndex = e.NewPageIndex;
            FillData();
        }

        protected void GrdList_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName == "detail")//aa是关联的事件名
            {
                int index = Convert.ToInt32(e.CommandArgument);//获取命令的参数
                int id = Convert.ToInt32(GetVal(index, 0));//获取当前点击列的ID号
                Response.Redirect("TaskDetail.aspx?id=" + id);
            }
        }

        protected void btnSearch_Click(object sender, EventArgs e)
        {
            var key = this.txtKey.Text.Trim();

            var sql = string.Format("select * from Task where TaskName like '%{0}%' or TaskContent like '%{1}%'", key, key);

            var dt = DbHelper.GetData(sql);

            GrdList.DataSource = dt;
            GrdList.DataBind();
        }

        protected void btnClear_Click(object sender, EventArgs e)
        {
            this.txtKey.Text = "";
            FillData();
        }
    }
}